﻿using Microsoft.IdentityModel.Tokens;
using SmartParkingServer.IDAL;
using SmartParkingServer.IService;
using SmartParkingServer.Models;
using SmartParkingServer.Service;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace SmartParkingServer.IServer
{
    public class UserService : BaseService, IUserService
    {
        public UserService(IDbContext dbConfig) : base(dbConfig)
        {
        }

        public bool Login(string username, string pwd,out UserModel userModel)
        {
            string password = GetMD5Str(GetMD5Str(pwd) + "|" + username);

            var users = this.Query<UserModel>(u => u.UserName == username && u.Password == password).ToList();
            userModel = users.FirstOrDefault();

            if (users.Count > 0 && this.AuthentationToken(username, out string token))
                userModel.Token = token;

            return users.Any();
        }

        // 需要进行重置密码的时候 ，做123456密码的加密处理再更新到对应的用户


        //登录密码处理
        //重置密码
        //只针对一次加密   

        private string GetMD5Str(string inputStr)
        {
            if (string.IsNullOrEmpty(inputStr)) return "";

            byte[] result = Encoding.Default.GetBytes(inputStr);    //tbPass为输入密码的文本框
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");  //tbMd5pass为输出加密文本的文本框
        }

        /// <summary>
        /// 身份验证Token  就是计算token
        /// </summary>
        /// <param name="username"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private bool AuthentationToken(string username, out string token)
        {
            token = string.Empty;
            if (string.IsNullOrEmpty(username))
                return false;

            var claims = new[]
            {
                new Claim(ClaimTypes.Name,username)
            };

            // 密码   必须是16位  通过特定方式进行加密
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("123456123456123456"));//随便写的 保证16位就行
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(
                "webapi.cn",
                "WebApi",
                claims,
                expires: DateTime.Now.AddMinutes(30),//超时时间
                signingCredentials: credentials);

            token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

            return true;
        }
    }
}
